package com.jicheng.service.impl;


import com.jicheng.dto.integrity.ReportDto;
import com.jicheng.dto.integrity.ReportPagingParams;
import com.jicheng.dto.integrity.ReportParams;
import com.jicheng.entity.ReportManagement;
import com.jicheng.ext.dto.PagingResult;
import com.jicheng.ext.enums.ApiResponseCode;
import com.jicheng.ext.exceptions.BaseException;
import com.jicheng.ext.util.BeanConvertor;
import com.jicheng.ext.util.UUIDUtils;
import com.jicheng.mapper.ReportManagementMapper;
import com.jicheng.service.IIntegrityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class IntegrityServiceImpl implements IIntegrityService {

    @Autowired
    private ReportManagementMapper reportManagementMapper;

    @Transactional
    @Override
    public void saveReport(ReportParams params) {
        notNull("params",params);
        notNull("params",params.getPeriod());
        if (params.getBeginTime() != null && params.getEndTime() != null) {
            if (params.getEndTime().getTime() < params.getBeginTime().getTime()) {
                throw new BaseException(ApiResponseCode.不允许此操作, "开始时间不能小于结束时间");
            }
//            if (params.getFinishTime().getTime()>params.getEndTime().getTime() ||
//                    params.getFinishTime().getTime()< params.getBeginTime().getTime()) {
//                throw new BaseException(ApiResponseCode.不允许此操作, "开始时间不能小于结束时间");
//            }
        }
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
//        String year = sdf.format(params.getFinishTime());

        ReportManagement reportManagement = BeanConvertor.copy(params, ReportManagement.class);
//        reportManagement.setYear(year);

        if (StringUtils.isEmpty(reportManagement.getId())) {
            reportManagement.setId(UUIDUtils.uuid());
            reportManagementMapper.insertSelective(reportManagement);
        } else {
            reportManagementMapper.updateByPrimaryKeySelective(reportManagement);
        }

    }

    @Override
    public PagingResult<ReportDto> getList(ReportPagingParams params) {
        notNull("params",params);
        PagingResult<ReportDto> result = new PagingResult();
        List<ReportDto> list = reportManagementMapper.getList(params);
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        result.setList(list);
        result.setTotal(reportManagementMapper.getCount(params));
        return result;
    }
}
